local Msg = require("core.Msg")
local Grid = require("bag.Grid")
local FuwenDefine = require("fuwen.FuwenDefine")
local FuwenGrid = require("fuwen.FuwenGrid")
local HeroLogic = require("hero.HeroLogic")
local FuwenExcel = require("excel.fuwen")
local ItemDefine = require("bag.ItemDefine")
local BagLogic = require("bag.BagLogic")
local ObjHuman = require("core.ObjHuman")
local RoleAttr = require("role.RoleAttr")
local Util = require("common.Util")
local LogDefine = require("common.LogDefine")
local Log = require("common.Log")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local HeroEquip = require("hero.HeroEquip")
local HeroExcel = require("excel.hero").hero
local RoleDBLogic = require("role.RoleDBLogic")
local BingshuLogic = require("fuwen.BingshuLogic")
local LiLianLogic = require("dailyTask.LiLianLogic")
local ChengjiuLogic = require("chengjiu.ChengjiuLogic")
local ChengjiuDefine = require("chengjiu.ChengjiuDefine")
local MailManager = require("mail.MailManager")
local MailExcel = require("excel.mail")
local HeroGrowUp = require("absAct.HeroGrowUp")
local YunYingLogic = require("yunying.YunYingLogic")

--发送所有符文列表 onLogin
function sendFuwenRefineList(human)
	local msgRet = Msg.gc.GC_FUWEN_ALL_LIST
	
    -- 发送 背包符文列表
	local fuwenMsgCnt = 0
    msgRet.isEnd = 0
    for index,fuwenGrid in pairs(human.db.fuwenBag) do
		if fuwenGrid and FuwenExcel.fuwen[fuwenGrid.id].refine == 1 then
			fuwenMsgCnt = fuwenMsgCnt + 1

			Grid.makeItem(msgRet.list[fuwenMsgCnt].fuwen, fuwenGrid.id, 1, nil, fuwenGrid, index,Grid.getOpflagAtBag(fuwenGrid.id))
			msgRet.list[fuwenMsgCnt].pos = 0
            msgRet.list[fuwenMsgCnt].heroID = 0
            msgRet.list[fuwenMsgCnt].heroIndex = 0

            -- 分包发送
			if fuwenMsgCnt >= FuwenDefine.PAGE_LIST_COUNT then
				msgRet.list[0] = fuwenMsgCnt 
				fuwenMsgCnt = 0
				Msg.send(msgRet, human.fd)
			end
		end
	end
	
    -- 英雄符文列表
    for index,heroGrid in pairs(human.db.heroBag) do
        if index ~= 0 and heroGrid.fuwen then
            for j = 1,2 do
                if heroGrid.fuwen[j] 
                and heroGrid.fuwen[j].id 
                and FuwenExcel.fuwen[heroGrid.fuwen[j].id].refine == 1 then
                    local fuwenGrid = heroGrid.fuwen[j]
                    fuwenMsgCnt = fuwenMsgCnt + 1
			        Grid.makeItem(msgRet.list[fuwenMsgCnt].fuwen, fuwenGrid.id, 1, nil, fuwenGrid, index,Grid.getOpflagAtBag(fuwenGrid.id))
			        msgRet.list[fuwenMsgCnt].pos = j
                    msgRet.list[fuwenMsgCnt].heroID = heroGrid.id
                    msgRet.list[fuwenMsgCnt].heroIndex = index

                    -- 分包发送
                    if fuwenMsgCnt >= FuwenDefine.PAGE_LIST_COUNT then
			        	msgRet.list[0] = fuwenMsgCnt 
			        	fuwenMsgCnt = 0
			        	Msg.send(msgRet, human.fd)
			        end
                end
            end
        end
    end

	msgRet.list[0] = fuwenMsgCnt 
    msgRet.isEnd = 1
	Msg.send(msgRet, human.fd)
end

-- 发送符文背包列表
function sendFuwenBagList(human)
	local msgRet = Msg.gc.GC_FUWEN_BAG_LIST
	
	local fuwenMsgCnt = 0
	for index,fuwenGrid in pairs(human.db.fuwenBag) do
		if fuwenGrid then
			fuwenMsgCnt = fuwenMsgCnt + 1
			Grid.makeItem(msgRet.list[fuwenMsgCnt], fuwenGrid.id, 1, nil, fuwenGrid, index, Grid.getOpflagAtBag(fuwenGrid.id))
			
			if fuwenMsgCnt >= FuwenDefine.PAGE_LIST_COUNT then
				msgRet.list[0] = fuwenMsgCnt 
				fuwenMsgCnt = 0
				Msg.send(msgRet, human.fd)
			end
		end
	end
	
	if fuwenMsgCnt > 0 then
		msgRet.list[0] = fuwenMsgCnt 
		Msg.send(msgRet, human.fd)
	end
end

-- 发送符文改变
function sendFuwenItemChange(human, bagIndex, fuwenGrid, op)
	local msgRet = Msg.gc.GC_FUWEN_BAG_CHANGE

	if op == FuwenDefine.FUWEN_BAG_OP_ADD or op == FuwenDefine.FUWEN_BAG_OP_CHANGE then
		msgRet.itemID = fuwenGrid.id
		msgRet.itemIndex = bagIndex
		Grid.makeItem(msgRet.itemData[1], fuwenGrid.id, 1, nil, fuwenGrid, bagIndex, Grid.getOpflagAtBag(fuwenGrid.id))
		msgRet.itemData[0] = 1

	elseif op == FuwenDefine.FUWEN_BAG_OP_DEL then
		msgRet.itemID = 0
		msgRet.itemIndex = bagIndex
		msgRet.itemData[0] = 0

	else 
		assert(nil)
	end
	
	Msg.send(msgRet, human.fd)
end

-- 添加新符文
function add(human, itemID, itemCnt, logType)
	local index = nil
    if itemID == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_ITEMID_ERR)
    end

    if itemCnt < 1 then
		return Broadcast.sendErr(human,Lang.FUWEN_ITEM_CNT_ERR)
	end

	for i = 1, itemCnt do
		local gridTemp = FuwenGrid.create(itemID)
        index = FuwenGrid.getEmptyIndex(human)

        if index ~= nil then
            human.db.fuwenBag[index] = gridTemp		
            sendFuwenItemChange(human, index, gridTemp, FuwenDefine.FUWEN_BAG_OP_ADD)
            Log.write(Log.LOGID_OSS_FUWEN, human.db._id, human.db.account, human.db.name, human.db.lv, LogDefine.DEFINE[logType] + LogDefine.TYPE["fuwen"] , itemID, 1)
        else
            -- 没有空格子了
            break
        end
        
        LiLianLogic.onCallback(human,LiLianLogic.LILIAN_OUTID28,itemCnt,itemID)
	end

    return index
end

-- 通过gird添加符文
function addByGrid(human, fuwenGrid, logType)
    if fuwenGrid == nil or fuwenGrid.id == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_GRID_ERR)
    end

    local index = FuwenGrid.getEmptyIndex(human)

    if not index then
       local items = {}
	   items[1] = { fuwenGrid.id, fuwenGrid }
   	   local title = MailExcel.mail[1000].title
	   local content = MailExcel.mail[1000].content
	   local senderName = MailExcel.mail[1000].senderName
	   MailManager.add(MailManager.SYSTEM, human.db._id, title, content, items, senderName)
       return
    end

    human.db.fuwenBag[index] = fuwenGrid		
    sendFuwenItemChange(human, index, fuwenGrid, FuwenDefine.FUWEN_BAG_OP_ADD)
    Log.write(Log.LOGID_OSS_FUWEN, human.db._id, human.db.account, human.db.name, human.db.lv, LogDefine.DEFINE[logType] + LogDefine.TYPE["fuwen"] , fuwenGrid.id, 1)		
    return index
end

-- 从背包删除符文
function del(human, index, logType)
	local fuwenGrid = human.db.fuwenBag[index]
	if fuwenGrid == nil then
		return Broadcast.sendErr(human,Lang.FUWEN_GRID_ERR)
	end
	
	human.db.fuwenBag[index] = nil
	
	Log.write(Log.LOGID_OSS_FUWEN, human.db._id, human.db.account, human.db.name, human.db.lv, LogDefine.DEFINE[logType] + LogDefine.TYPE["fuwen"] , fuwenGrid.id, -1)	
	
	sendFuwenItemChange(human, index, nil, FuwenDefine.FUWEN_BAG_OP_DEL)
end

-- 穿上符文
function putOn(human, heroID, heroIndex, fuwenIndex,pos,noCalc)
    local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	if heroGrid == nil then
		return Broadcast.sendErr(human,Lang.FUWEN_HERO_GRID_ERR)
	end

    local fuwenGrid = human.db.fuwenBag[fuwenIndex]
	if fuwenGrid == nil then
		return
	end

    if heroGrid.fuwen == nil or heroGrid.fuwen[pos] == nil then
        return
    else
        if heroGrid.fuwen[pos].id == nil then
            -- 新穿装备
            del(human, fuwenIndex, "fuwen_puton")
            heroGrid.fuwen = heroGrid.fuwen or {}
            heroGrid.fuwen[pos] = fuwenGrid
        else
            -- 替换装备
            local oldFuwenGrid = heroGrid.fuwen[pos]
            del(human, fuwenIndex, "fuwen_puton")
            addByGrid(human, oldFuwenGrid, "fuwen_putoff")
            heroGrid.fuwen[pos] = fuwenGrid
        end
    end

	if noCalc ~= true then
		-- 计算属性    todo 
		ObjHuman.doCalcHero(human,heroIndex)
        HeroLogic.sendHeroBagDynamic(human, heroID, heroIndex)	
        HeroEquip.query(human, heroID, heroIndex)	
	end
    
	-- 通知客户端
	local msgRet = Msg.gc.GC_FUWEN_PUTON
	msgRet.heroID = heroID
	msgRet.heroIndex = heroIndex
    msgRet.pos = pos
    Grid.makeItem(msgRet.fuwen, fuwenGrid.id, 1, nil, fuwenGrid, -1, Grid.getOpflagAtBag(fuwenGrid.id))
	Msg.send(msgRet, human.fd)
end

-- 脱下符文
function putOff(human, heroID, heroIndex, pos, noCalc)
    local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	if heroGrid == nil then
		return 
	end
    
    if heroGrid.fuwen == nil or heroGrid.fuwen[pos] == nil or heroGrid.fuwen[pos].id == nil then
        return 
    end

    if not FuwenGrid.checkEmptyCnt(human, 1) then
       return
    end

    local oldFuwenGrid = heroGrid.fuwen[pos]
    heroGrid.fuwen[pos] = {}
    addByGrid(human, oldFuwenGrid, "fuwen_putoff")

    if noCalc ~= true then
		-- 计算属性
		ObjHuman.doCalcHero(human,heroIndex)
        HeroLogic.sendHeroBagDynamic(human, heroID, heroIndex)
        HeroEquip.query(human, heroID, heroIndex)	
	end

    -- 通知客户端
	local msgRet = Msg.gc.GC_FUWEN_PUTOFF
	msgRet.heroID = heroID
	msgRet.heroIndex = heroIndex
    msgRet.pos = pos
	Msg.send(msgRet, human.fd)
end

function putOffQuick(human, heroID, heroIndex, noSys)
	putOff(human, heroID, heroIndex, 1, true)
	putOff(human, heroID, heroIndex, 2, true)

    if not noSys then
	   ObjHuman.doCalcHero(human,heroIndex)
       HeroLogic.sendHeroBagDynamic(human, heroID, heroIndex)
       HeroEquip.query(human, heroID, heroIndex)
    end	
end

-- 符文合成查询
local cacheFuwenGrid = {}
function fuwenHechengQuery(human,fuwenID,fuwenCnt)
    local hechengConfig = FuwenExcel.hechengRule[fuwenID]
	if hechengConfig == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_CONFIG_ERR)
    end
	
	local fuwenConfig = FuwenExcel.fuwen[fuwenID]
    if fuwenConfig == nil then
       return
    end

    local sub = fuwenCnt - 1
    local costJinbi = hechengConfig.hechengCost[sub]
    local succRate = hechengConfig.hechengRate[sub]
    local newFuwenID = hechengConfig.newFuwenID
    local failSmeltVal = hechengConfig.failRonglian

    local msgRet = Msg.gc.GC_FUWEN_HECHENG_QUERY
    msgRet.costJinbi = costJinbi
    msgRet.successRate = succRate
    if fuwenCnt < 2 then
        msgRet.costJinbi = 0
        msgRet.successRate = 0
    end

    if cacheFuwenGrid[newFuwenID] == nil then
        cacheFuwenGrid[newFuwenID] = FuwenGrid.create(newFuwenID)
    end

    local fuwenGrid = cacheFuwenGrid[newFuwenID] 
    Grid.makeItem(msgRet.newFuwen, newFuwenID, 1, nil, fuwenGrid, 1)

    msgRet.smeltVal = failSmeltVal
    msgRet.accountSmeltVal = human.db.smeltVal or 0 
    msgRet.desc1 = hechengConfig.desc1
    msgRet.desc2 = hechengConfig.desc2

	local newFuwenConfig = FuwenExcel.fuwen[newFuwenID]
	wrapFuwenAttrNet(msgRet,newFuwenConfig)

	Msg.send(msgRet,human.fd)
end

-- 合成符文
function fuwenHechengDo(human,fuwenIndexList)
    if human.db.lv < 30 then
        return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_LIMIT)
    end
    -- 校验材料个数
    local cnt = fuwenIndexList[0]
    if cnt < 2 then
        return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_CNR_ERR)
    end

    local newFuwenID = nil
    local oldFuwenID = nil
    local config = FuwenExcel.hechengRule
	local indexTable = {}

    for i = 1,cnt do
        -- 防止添加同一个符文
        local index = fuwenIndexList[i]
		if indexTable[index] then
		   return
		end

        -- 背包中没有该符文
        if human.db.fuwenBag[index] == nil then
            return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_FILL_ERR)
        end

        -- 校验材料是否相同
        local fuwenGrid = human.db.fuwenBag[index]
        if oldFuwenID == nil then
            oldFuwenID = fuwenGrid.id
        else
            if oldFuwenID ~= fuwenGrid.id then
                return Broadcast.sendErr(human,Lang.FUWEN_ID_ERR)
            end
        end
		indexTable[index] = true
    end

    -- 校验是否有合成配置
    local hechengConfig = FuwenExcel.hechengRule[oldFuwenID]
    if hechengConfig == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_CONFIG_ERR)
    end

    -- 校验是否达到合成限制等级
    if hechengConfig.limit > human.db.lv then
        return Broadcast.sendErr(human,Util.format(Lang.ROLE_LV_TOO_LOW, hechengConfig.limit))
    end

    -- 校验金币数量够不够
    local costJinbi = hechengConfig.hechengCost[cnt - 1]
    if human.db.jinbi < costJinbi then
        return Broadcast.sendErr(human,Lang.COMMON_NO_JINBI)
    end

    newFuwenID = hechengConfig.newFuwenID
    local rate = hechengConfig.hechengRate[cnt - 1]
    
    ObjHuman.updateJinbi(human, -costJinbi, "fuwen_hecheng")	

    local randomNum = math.random(1,100)
    local newFuwenGrid = nil
    local fenjieList = {}
    if randomNum <= rate then
        -- 合成成功
        for i = 1,cnt do
            local index = fuwenIndexList[i]
            del(human, index, "fuwen_hecheng")
        end

        local msgRet = Msg.gc.GC_FUWEN_HECHENG_SUCCESS
        newFuwenGrid = FuwenGrid.create(newFuwenID)

        local newIndex = addByGrid(human, newFuwenGrid, "fuwen_hecheng")
        Grid.makeItem(msgRet.fuwen, newFuwenGrid.id, 1, nil, newFuwenGrid, newIndex,0)
        Msg.send(msgRet,human.fd)
    else
        -- 合成失败
        for i = 1,cnt do
            local index = fuwenIndexList[i]
            local fenjieConfig = FuwenExcel.fuwen[oldFuwenID]
            del(human, index, "fuwen_fenjie")

            local jhCnt = math.floor(fenjieConfig.fenjieJinghua/2)
            fenjieList[ItemDefine.ITEM_FUWEN_JINGHUA] = fenjieList[ItemDefine.ITEM_FUWEN_JINGHUA] or 0
            fenjieList[ItemDefine.ITEM_FUWEN_JINGHUA] = fenjieList[ItemDefine.ITEM_FUWEN_JINGHUA] + jhCnt

        end
        BagLogic.addItemList(human, fenjieList, "fuwen_fenjie")
        
        local baseCnt = hechengConfig.failRonglian
        local failRonglian_cnt = baseCnt + math.floor((cnt-2) * baseCnt/2)

        human.db.smeltVal = human.db.smeltVal or 0
        human.db.smeltVal = human.db.smeltVal + failRonglian_cnt

        local fenjieConfig = FuwenExcel.fuwen[oldFuwenID]
        local fenjieJinghua_cnt = math.floor(fenjieConfig.fenjieJinghua/2) * cnt

        local msgRet = Msg.gc.GC_FUWEN_HECHENG_FAIL
        msgRet.smeltVal = hechengConfig.failRonglian
        msgRet.accountSmeltVal = human.db.smeltVal
        Grid.makeItem(msgRet.fuwenJinghua, ItemDefine.ITEM_FUWEN_JINGHUA, fenjieJinghua_cnt)

        Msg.send(msgRet,human.fd)
    end

    -- 符文合成回调
    ChengjiuLogic.onCallback(human,ChengjiuDefine.CJ_TASK_TYPE_22,1)
	HeroGrowUp.onCallback(human, HeroGrowUp.TASKTYPE8, 1)
    YunYingLogic.onCallBack(human, "onFuwenHecheng",1)   

end

-- 分解符文
function fuwenFenjieDo(human,fuwenID,fuwenIndex,fenjieType)
    -- 校验符文是否可分解
    local fenjieConfig = FuwenExcel.fuwen[fuwenID]
    if fenjieConfig == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_FENJIE_CONFIG_ERR)
    end

    -- 符文为空
    local fuwenGrid = human.db.fuwenBag[fuwenIndex] 
    if fuwenGrid == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_GRID_ERR)
    end

    -- 符文对不上
    if fuwenGrid.id ~= fuwenID then
        return Broadcast.sendErr(human,Lang.FUWEN_ID_ERR)
    end

    del(human, fuwenIndex, "fuwen_fenjie")

    local fenjieList = {}
    if fenjieType == nil then
        local msgRet = Msg.gc.GC_FUWEN_FENJIE
        Msg.send(msgRet,human.fd)
        fenjieList[ItemDefine.ITEM_FUWEN_JINGHUA] = fenjieConfig.fenjieJinghua
    else
        local cnt = math.floor(fenjieConfig.fenjieJinghua/2)
        fenjieList[ItemDefine.ITEM_FUWEN_JINGHUA] = cnt
    end

    BagLogic.addItemList(human, fenjieList, "fuwen_fenjie")
end

-- 符文兑换
function fuwenExhcange(human)
    if human.db.smeltVal == nil or human.db.smeltVal < FuwenDefine.FUWEN_EXCHANGE_CNT then
        return Broadcast.sendErr(human,Lang.FUWEN_EXCHANGE_ERR)         -- 熔炼值不够
    end 

    human.db.smeltVal = human.db.smeltVal - FuwenDefine.FUWEN_EXCHANGE_CNT

    local index = add(human, FuwenDefine.FUWEN_EXCHANGE_ID, 1, "fuwen_exchange")
    local fuwenGrid = human.db.fuwenBag[index]

    local msgRet = Msg.gc.GC_FUWEN_EXCHANGE
    if fuwenGrid ~= nil then
         Grid.makeItem(msgRet.fuwen, fuwenGrid.id, 1, nil, fuwenGrid, 1)
         Msg.send(msgRet,human.fd)
    end

    fuwenSmeltValQuery(human)
end

-- 符文刷新查询
function fuwenRefreshQuery(human,fuwenID,fuwenIndex,pos,heroID,heroIndex)
    local fuwen = nil

    if fuwenIndex == -1 then
        -- 英雄身上符文
        local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	    if heroGrid == nil then
	    	return Broadcast.sendErr(human,Lang.FUWEN_HERO_GRID_ERR)
	    end

        if heroGrid.fuwen == nil or heroGrid.fuwen[pos] == nil then
            return Broadcast.sendErr(human,Lang.FUWEN_PUTOFF_ERR)
        end

        fuwen = heroGrid.fuwen[pos]
    else
        fuwen = human.db.fuwenBag[fuwenIndex] 
    end
    
    if fuwen == nil or fuwen.id == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_FILL_ERR)     -- 材料不存在
    end

    if fuwen.id ~= fuwenID then
        return Broadcast.sendErr(human,Lang.FUWEN_ID_ERR)
    end

    local refreshConfig = FuwenExcel.fuwen[fuwenID]
    if refreshConfig == nil then 
        return Broadcast.sendErr(human,Lang.FUWEN_REFRESH_CONFIG_ERR)     -- 没有相关id分解配置
    end

    if human.db.fuwenRefreshCnt == nil then
        human.db.fuwenRefreshCnt = {}
        human.db.fuwenRefreshCnt.sh = 0
        human.db.fuwenRefreshCnt.cs = 0
    end

    local msgRet = Msg.gc.GC_FUWEN_REFRESH_QUERY
    
    -- 本体符文
    Grid.makeItemFuwen(msgRet.fuwen,fuwen.id,FuwenExcel.fuwen[fuwen.id],fuwen,fuwenIndex)
    -- 临时符文
    Grid.makeItemFuwen(msgRet.fuwenTemp,fuwen.id,FuwenExcel.fuwen[fuwen.id],fuwen,fuwenIndex)
    if fuwen.attrTemp == nil then 
        fuwen.attrTemp = {}
    end

    -- 临时属性备份
    local attrLen = #fuwen.attrTemp
	for zz = 1,attrLen do
		msgRet.fuwenTemp.attrs[zz].key = fuwen.attrTemp[zz][1]
		msgRet.fuwenTemp.attrs[zz].value = fuwen.attrTemp[zz][2]
	end
	msgRet.fuwenTemp.attrs[0] = attrLen

    -- 临时技能备份
	if fuwen.skillTemp == nil then
		msgRet.fuwenTemp.skills[0] = 0
	else
        local skillLen = #fuwen.skillTemp
		for zz = 1,skillLen do
            Grid.makeFuwenSkill(msgRet.fuwenTemp.skills[zz], fuwen.skillTemp[zz])
		end
		msgRet.fuwenTemp.skills[0] = skillLen
	end

	if attrLen == 0 and fuwen.skillTemp == nil then
        msgRet.fuwenTemp.id = 0
    else
        msgRet.fuwenTemp.id = fuwen.id
    end

    local lenth = #refreshConfig.expend
    for i = 1,lenth do
        Grid.makeItem(msgRet.expend[i],refreshConfig.expend[i][1],refreshConfig.expend[i][2])
    end
    msgRet.expend[0] = lenth

    msgRet.refreshCnt = 0
    if refreshConfig.rare == ItemDefine.ITEM_RARE_COLOR_5 then
        msgRet.refreshCnt = human.db.fuwenRefreshCnt.sh
    elseif refreshConfig.rare == ItemDefine.ITEM_RARE_COLOR_6 then
        msgRet.refreshCnt = human.db.fuwenRefreshCnt.cs
    end
    msgRet.needCnt = refreshConfig.luckRefresh or 0

    Msg.send(msgRet,human.fd)
end

-- 符文刷新
function fuwenRefreshDo(human,fuwenID,fuwenIndex,heroID,heroIndex,pos)
    local refreshConfig = FuwenExcel.fuwen[fuwenID]
    if refreshConfig == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_REFRESH_CONFIG_ERR)     -- 传入参数非法
    end
    
    local fuwenGrid = nil
    if fuwenIndex == -1 then        -- 刷英雄身上的
        local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	    if heroGrid == nil then
	    	return Broadcast.sendErr(human,Lang.FUWEN_HERO_GRID_ERR)         -- 传入的英雄数据非法
	    end

        if pos == nil then
            return Broadcast.sendErr(human,Lang.FUWEN_PUTOFF_ERR)        -- 传入的参数非法
        end

        if heroGrid.fuwen == nil or heroGrid.fuwen[pos] == nil or heroGrid.fuwen[pos].id == nil then
            return Broadcast.sendErr(human,Lang.FUWEN_PUTOFF_ERR)         -- 传入的参数非法
        end

        fuwenGrid = heroGrid.fuwen[pos]
    else                            -- 刷背包里的
        if human.db.fuwenBag == nil or human.db.fuwenBag[fuwenIndex] == nil then
            return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_FILL_ERR)     -- 材料不存在
        end

        fuwenGrid = human.db.fuwenBag[fuwenIndex]
    end

    if fuwenGrid == nil or fuwenGrid.id == nil then
        return
    end

    if fuwenGrid.id ~= nil and fuwenGrid.id ~= fuwenID then
        return Broadcast.sendErr(human,Lang.FUWEN_ID_ERR)
    end 

    -- 幸运重铸判定
    local luckRefresh = 0
    local refreshCnt = 0
    human.db.fuwenRefreshCnt.cs = human.db.fuwenRefreshCnt.cs or 0
    human.db.fuwenRefreshCnt.sh = human.db.fuwenRefreshCnt.sh or 0

    if refreshConfig.rare == ItemDefine.ITEM_RARE_COLOR_5 then
        refreshCnt = human.db.fuwenRefreshCnt.sh or 0
    elseif refreshConfig.rare == ItemDefine.ITEM_RARE_COLOR_6 then
        refreshCnt = human.db.fuwenRefreshCnt.cs or 0 
    end

    if refreshConfig.luckRefresh ~= nil and refreshConfig.luckRefresh ~= 0 and refreshCnt >= refreshConfig.luckRefresh then
        luckRefresh = 1
    end

    local jinghuaCnt = BagLogic.getItemCnt(human, ItemDefine.ITEM_FUWEN_JINGHUA)
    if human.db.jinbi < refreshConfig.expend[1][2] or jinghuaCnt < refreshConfig.expend[2][2] then
        return Broadcast.sendErr(human,Lang.FUWEN_REFRESH_FILL_ERR)   -- 材料不够
    end

    if refreshConfig.rare == ItemDefine.ITEM_RARE_COLOR_5 then
        human.db.fuwenRefreshCnt.sh = human.db.fuwenRefreshCnt.sh + 1
    elseif refreshConfig.rare == ItemDefine.ITEM_RARE_COLOR_6 then
        human.db.fuwenRefreshCnt.cs = human.db.fuwenRefreshCnt.cs + 1
    end
    
    if human.db.fuwenRefreshCnt.cs > 15 then
        human.db.fuwenRefreshCnt.cs = 0
    end

    if human.db.fuwenRefreshCnt.sh > 25 then
        human.db.fuwenRefreshCnt.sh = 0
    end

    -- 扣消耗
    local fuwenGridTemp = Util.copyTable(fuwenGrid)
    ObjHuman.updateJinbi(human, -refreshConfig.expend[1][2], "fuwen_refresh")	
    BagLogic.delItem(human, ItemDefine.ITEM_FUWEN_JINGHUA, refreshConfig.expend[2][2], "fuwen_refresh")	

    -- 改属性
    FuwenGrid.genFuwenAttr(fuwenGridTemp,luckRefresh)
    fuwenGrid.attrTemp = fuwenGridTemp.attr or {}
    fuwenGrid.skillTemp = fuwenGridTemp.skill

    local msgRet = Msg.gc.GC_FUWEN_REFRESH_DO
    Grid.makeItem(msgRet.fuwen, fuwenGridTemp.id, 1, nil, fuwenGridTemp, fuwenIndex)
    Msg.send(msgRet,human.fd)

    fuwenRefreshQuery(human,fuwenID,fuwenIndex,pos,heroID,heroIndex)
end

local function cmpSkill(a, b)
    if a.sortID ~= b.sortID then
        return  a.sortID < b.sortID
    end
    return a.skillID < b.skillID
end

local SORT_SKILL_LIST = nil
function getSortSkillList()
    if not SORT_SKILL_LIST then
        SORT_SKILL_LIST = {}
        for skillID, config in pairs(FuwenExcel.skill) do
            config.skillID = skillID
            SORT_SKILL_LIST[#SORT_SKILL_LIST + 1] = config
        end
        if #SORT_SKILL_LIST > 1 then
            table.sort(SORT_SKILL_LIST, cmpSkill)
        end
    end
    return SORT_SKILL_LIST
end

-- 技能查询
function fuwenRareSkillQuery(human, lv)
    local configs = getSortSkillList()
    local msgRet = Msg.gc.GC_FUWEN_RARE_SKILL_QUERY
    msgRet.type = lv
    local cnt = 0
	for _, config in ipairs(configs) do
        if config.lv == lv then
		    cnt = cnt + 1
            Grid.makeFuwenSkill(msgRet.skillInfo[cnt], config.skillID)
		end
	end
	if cnt > 0 then
		msgRet.skillInfo[0] = cnt 
		Msg.send(msgRet, human.fd)
	end
end

-- 计算属性
local tbSkillGroupID = {}
function doCalcHero(obj,attrs)
    Util.initTable(tbSkillGroupID)  
    if obj.fuwen then    	
    	for i = 1, 2 do
    		local fuwenGrid = obj.fuwen[i]
            if fuwenGrid and fuwenGrid.id ~= nil then	
                for k, v in ipairs(fuwenGrid.attr) do
                    RoleAttr.updateValue(v[1], v[2], attrs)
    			end

                local skillLen = fuwenGrid.skill and #fuwenGrid.skill or 0
                for j = 1, skillLen do
                    local skillID = fuwenGrid.skill[j]
                    local skillConfig = FuwenExcel.skill[skillID]
                    local groupID = skillConfig.groupID

                    if (tbSkillGroupID[groupID] or 0) < skillID then
    					tbSkillGroupID[groupID] = skillID
                    end
                end
    		end
    	end
    end

    -- 兵书技能
    if obj.bingshu then
        for i = 1, BingshuLogic.BINGSHU_MAXCNT do
            local bingshuGrid = obj.bingshu[i]
            if bingshuGrid then
                local skillID = bingshuGrid.skillID
                local skillConfig = FuwenExcel.skill[skillID]
                local groupID = skillConfig.groupID
                if (tbSkillGroupID[groupID] or 0) < skillID then
                    tbSkillGroupID[groupID] = skillID
                end             
            end
        end
    end
	
	-- 符文技能效果这里 如果有多个同类型的技能 效果不叠加 只取最高等级的那个技能的效果
	for groupID, skillIDTemp in pairs(tbSkillGroupID) do
		local skillConfig = FuwenExcel.skill[skillIDTemp]
	    local cnt = #skillConfig.attrs
        if cnt > 0 then
            for k, v in ipairs(skillConfig.attrs) do
                RoleAttr.updateValue(v[1], v[2], attrs)
		    end
        end
	end
end

-- 熔炼值查询
function fuwenSmeltValQuery(human)
    local msgRet = Msg.gc.GC_FUWEN_SMELT_VAL_QUERY
    msgRet.accountSmeltVal = human.db.smeltVal or 0
    Msg.send(msgRet,human.fd)
end

-- 符文刷新保存
function fuwenRefreshSave(human,fuwenID,fuwenIndex,pos,heroID,heroIndex)
    local fuwen = nil
    if fuwenIndex == -1 then
        local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	    if heroGrid == nil then
	    	return Broadcast.sendErr(human,Lang.FUWEN_HERO_GRID_ERR)
	    end

        if heroGrid.fuwen == nil or heroGrid.fuwen[pos] == nil then
            return Broadcast.sendErr(human,Lang.FUWEN_PUTOFF_ERR)
        end

        fuwen = heroGrid.fuwen[pos]
    else
        fuwen = human.db.fuwenBag[fuwenIndex] 
    end

    if fuwen == nil or fuwen.id == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_FILL_ERR)
    end

    if fuwen.id ~= fuwenID then
        return Broadcast.sendErr(human,Lang.FUWEN_ID_ERR)
    end

    if fuwen.attrTemp ~= nil or fuwen.skillTemp ~= nil then
        if next(fuwen.attrTemp) then
            fuwen.attr = fuwen.attrTemp
            fuwen.attrTemp = {}
        else
            Log.write(Log.LOGID_DEBUG, human.db._id, human.db.account, human.db.name, human.db.lv, fuwen.id,"refreshsave attrTemp is empty")	
        end
        if next(fuwen.skillTemp) then
            fuwen.skill = fuwen.skillTemp
            fuwen.skillTemp = nil
        else
            Log.write(Log.LOGID_DEBUG, human.db._id, human.db.account, human.db.name, human.db.lv, fuwen.id,"refreshsave skillTemp is empty")	
        end
    end

    Broadcast.sendErr(human,Lang.FUWEN_SAVE_SUCCESS)

    if fuwenIndex == -1 then
        ObjHuman.doCalcHero(human,heroIndex)
		HeroLogic.sendHeroBagDynamic(human, heroID, heroIndex)		
        HeroEquip.query(human, heroID, heroIndex)
    else
        sendFuwenItemChange(human, fuwenIndex, fuwen, FuwenDefine.FUWEN_BAG_OP_ADD)
    end

    fuwenRefreshQuery(human,fuwenID,fuwenIndex,pos,heroID,heroIndex)
end

-- 符文兑换查询
function fuwenExchangeQuery(human)
    local msgRet = Msg.gc.GC_FUWEN_EXCHANGE_QUERY
    local gridTemp = FuwenGrid.create(FuwenDefine.FUWEN_EXCHANGE_ID)
    Grid.makeItem(msgRet.fuwen, gridTemp.id, 1, nil, gridTemp, 1)
    Msg.send(msgRet,human.fd)
end

-- 符文格子解锁
function fuwenGridUnlock(human,heroID,heroIndex,pos)
    local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	if heroGrid == nil then
		return
	end

    if heroGrid.fuwen ~= nil and heroGrid.fuwen[pos] ~= nil then
        return
    end

    if pos == 1 then
        if heroGrid.lv < 100 then
        else
            heroGrid.fuwen = heroGrid.fuwen or {}
            heroGrid.fuwen[1] = {}
        end

    elseif pos == 2 then
        if heroGrid.star < 7 then
        else
            heroGrid.fuwen = heroGrid.fuwen or {}
            heroGrid.fuwen[2] = {}
        end
    end
end

function wrapFuwenAttrNet(net,fuwenConf)
    local len = 0
	for _,attr in ipairs(fuwenConf.absAttrPool) do
		len = len + 1
		net.base_attrs[len].key = attr[1]
		net.base_attrs[len].value = attr[2]
	end
	net.base_attrs[0] = len

    local len2 = 0
    for _, attr in ipairs(fuwenConf.percentAttrPool) do
        len2 = len2 + 1
        net.percent_attrs[len2].key = attr[1]
		net.percent_attrs[len2].value = attr[2]
    end
    net.percent_attrs[0] = len2
end

-- 符文属性查询
function CG_FUWEN_ATTR_QUERY(human,fuwenID)
    if fuwenID == nil then
       return Broadcast.sendErr(human,Lang.FUWEN_ITEMID_ERR)
    end

    local fuwenConfig = FuwenExcel.fuwen[fuwenID]
    if fuwenConfig == nil then
       return
    end

	local msgRet = Msg.gc.GC_FUWEN_ATTR_QUERY
    wrapFuwenAttrNet(msgRet,fuwenConfig)
    
    Msg.send(msgRet,human.fd)
end

-- 符文精炼预览
function fuwenRefinePreview(human)
    local fuwenGrid = {}
    fuwenGrid = FuwenGrid.create(FuwenDefine.FUWEN_REFINE_ID)
    local msgRet = Msg.gc.GC_FUWEN_REFINE_PREVIEW_QUERY
    Grid.makeItem(msgRet.fuwen, fuwenGrid.id, 1, nil, fuwenGrid, 1)
    Msg.send(msgRet,human.fd)
end

-- 符文精炼查询
function fuwenRefineQuery(human,fuwenID,fuwenIndex,pos,heroID,heroIndex)
    local fuwen = nil
    if fuwenIndex == -1 then
        local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	    if heroGrid == nil then
	    	return Broadcast.sendErr(human,Lang.FUWEN_HERO_GRID_ERR)
	    end

        if heroGrid.fuwen == nil or heroGrid.fuwen[pos] == nil then
            return Broadcast.sendErr(human,Lang.FUWEN_PUTOFF_ERR)
        end

        fuwen = heroGrid.fuwen[pos]
    else
        fuwen = human.db.fuwenBag[fuwenIndex] 
    end
    
    if fuwen == nil or fuwen.id == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_FILL_ERR)     -- 材料不存在
    end

    if fuwen.id ~= fuwenID then
        return Broadcast.sendErr(human,Lang.FUWEN_ID_ERR)
    end

    if FuwenExcel.fuwen[fuwen.id].refine ~= 1 then
        return
    end

    local jinglianExcel = FuwenExcel.jinglian
    local refine = fuwen.refine or 0
    local refineExcel = jinglianExcel[refine + 1]

    -- 构造预览符文
    local previewFuwen = Util.copyTable(fuwen)
    previewFuwen.refine = refine + 1
    if refine == 0 then
        -- 第1次精炼
        local newValue = previewFuwen.attr[1][2] * 2
        previewFuwen.attr[1][2] = newValue
    elseif refine == 1 then
        -- 第2次精炼
        local fuwenConfig = FuwenExcel.fuwen[fuwen.id]
        cnt = #fuwenConfig.percentAttrPool
        if cnt > 0 then
            local randIndex = math.random(1, cnt)
            local attrKey = fuwenConfig.percentAttrPool[randIndex][1]
            local attrVal = fuwenConfig.percentAttrPool[randIndex][2]
            previewFuwen.attr[3] = {attrKey, attrVal}
        end
    elseif refine == 2 then
        -- 第3次精炼
        local skillConfig = FuwenExcel.skill
        local skillLen = #previewFuwen.skill
        for i = 1,skillLen do
            local skillID = previewFuwen.skill[i] 
            local skillLv = skillConfig[skillID].lv
            if skillLv < 3 then
                skillID = skillID + 1000
            end
            previewFuwen.skill[i] = skillID
        end
        previewFuwen.id = fuwen.id + 1
    end

    -- 发数据
    local msgRet = Msg.gc.GC_FUWEN_REFINE_QUERY
    Grid.makeItem(msgRet.fuwen,previewFuwen.id, 1, nil,previewFuwen, 1)

    local expendLen = #refineExcel.expend
    for i = 1,expendLen do
        Grid.makeItem(msgRet.expend[i],refineExcel.expend[i][1],refineExcel.expend[i][2])
    end
    msgRet.expend[0] = expendLen
    local jinglianLen = #jinglianExcel
    for i = 1,jinglianLen do
        msgRet.refineDesc[i].desc = jinglianExcel[i].desc
    end
    msgRet.refineDesc[0] = jinglianLen

    Msg.send(msgRet,human.fd)
end

-- 符文精炼
function fuwenRefineDo(human,fuwenID,fuwenIndex,pos,heroID,heroIndex)
    local fuwen = nil
    if fuwenIndex == -1 then
        local heroGrid = HeroLogic.getHeroGrid(human, heroID, heroIndex)
	    if heroGrid == nil then
	    	return Broadcast.sendErr(human,Lang.FUWEN_HERO_GRID_ERR)
	    end

        if heroGrid.fuwen == nil or heroGrid.fuwen[pos] == nil then
            return Broadcast.sendErr(human,Lang.FUWEN_PUTOFF_ERR)
        end

        fuwen = heroGrid.fuwen[pos]
    else
        fuwen = human.db.fuwenBag[fuwenIndex] 
    end
    
    if fuwen == nil or fuwen.id == nil then
        return Broadcast.sendErr(human,Lang.FUWEN_HECHENG_FILL_ERR)     -- 材料不存在
    end

    if fuwen.id ~= fuwenID then
        return Broadcast.sendErr(human,Lang.FUWEN_ID_ERR)
    end

    if FuwenExcel.fuwen[fuwen.id].refine ~= 1 then
        return
    end

    local newRefine = fuwen.refine or 0
    newRefine = newRefine + 1
    local jinglianExcel = FuwenExcel.jinglian
    local refineExcel = jinglianExcel[newRefine]
        
    local expendLen = #refineExcel.expend
    for i = 1,expendLen do
        local v = refineExcel.expend[i]
        local haveCnt = BagLogic.getItemCnt(human,v[1])
        if haveCnt < v[2] then
            return Broadcast.sendErr(human,Lang.FUWEN_REFRESH_FILL_ERR)   -- 材料不够
        end
    end

    --删除材料
    for i = 1,expendLen do
        local v = refineExcel.expend[i]
        BagLogic.delItem(human, v[1], v[2], "fuwen_refine")	
    end

    if newRefine == 1 then
        -- 第1次精炼
        fuwen.refine = newRefine
        local newValue = fuwen.attr[1][2] * 2
        fuwen.attr[1][2] = newValue

    elseif newRefine == 2 then
        -- 第2次精炼
        fuwen.refine = newRefine
        local fuwenConfig = FuwenExcel.fuwen[fuwen.id]
        cnt = #fuwenConfig.percentAttrPool
        if cnt > 0 then
            local randIndex = math.random(1, cnt)
            local attrKey = fuwenConfig.percentAttrPool[randIndex][1]
            local attrVal = fuwenConfig.percentAttrPool[randIndex][2]
            fuwen.attr[3] = {attrKey, attrVal}
        end
    elseif newRefine == 3 then
        -- 第3次精炼
        fuwen.refine = newRefine

        local skillConfig = FuwenExcel.skill
        local skillLen = #fuwen.skill
        for i = 1,skillLen do
            local skillID = fuwen.skill[i] 
            local skillLv = skillConfig[skillID].lv
            if skillLv < 4 then
                skillID = skillID + 1000
            end
            fuwen.skill[i] = skillID
        end
        fuwen.id = fuwen.id + 1
        fuwen.refine = 0
    else
        return
    end

    if fuwenIndex == -1 then
        ObjHuman.doCalcHero(human,heroIndex)
		HeroLogic.sendHeroBagDynamic(human, heroID, heroIndex)		
        HeroEquip.query(human, heroID, heroIndex)
    else
        sendFuwenItemChange(human, fuwenIndex, fuwen, FuwenDefine.FUWEN_BAG_OP_ADD)
    end

    local msgRet = Msg.gc.GC_FUWEN_REFINE_DO
    Grid.makeItem(msgRet.fuwen,fuwen.id, 1,nil, fuwen, 1)

    Msg.send(msgRet,human.fd)
end

-- 是否有符文红点
function isFuwenDot(human, heroGrid)
	if not heroGrid then return end
	local heroConfig = HeroExcel[heroGrid.id]
	if not heroConfig then return end

    if human.db.lv < 9 then
       return false
    end

    local haveFuwen = nil
    local emptyCnt = FuwenGrid.getEmptyCnt(human)
    if emptyCnt < FuwenDefine.FUWEN_BAG_MAX_CNT then
        haveFuwen = true
    end

	for pos = 1, 2 do
        local fuwenGrid = heroGrid.fuwen and heroGrid.fuwen[pos]
		if fuwenGrid ~= nil and fuwenGrid.id == nil and haveFuwen then
            return true
		end
	end
end

-- 是否有装备红点
function isFuwenDotByPos(human, heroGrid, pos)
	if not heroGrid then return end
	local heroConfig = HeroExcel[heroGrid.id]
	if not heroConfig then return end

    local haveFuwen = nil
    local emptyCnt = FuwenGrid.getEmptyCnt(human)
    if emptyCnt < FuwenDefine.FUWEN_BAG_MAX_CNT then
        haveFuwen = true
    end
	
    local fuwenGrid = heroGrid.fuwen and heroGrid.fuwen[pos]
	if fuwenGrid ~= nil and fuwenGrid.id == nil and haveFuwen then
        return true
	end
end

function sendFuwenGetWay(human)
    local msgRet = Msg.gc.GC_FUWEN_GET_WAY_QUERY
    local fuwenGrid =  FuwenGrid.create(80001)
    local hechengConfig = FuwenExcel.hechengRule[80001]
    Grid.makeItem(msgRet.newFuwen, 80001, 1, nil, fuwenGrid, 1)
    msgRet.desc1 = hechengConfig.desc1
    msgRet.desc2 = hechengConfig.desc2
    Msg.send(msgRet,human.fd)
end